//
//  homeVC.m
//  FeiHuaJiaoYu
//
//  Created by 范智渊 on 2018/10/8.
//  Copyright © 2018 范智渊. All rights reserved.
//

#import "JMHomeVC.h"
#import "JMDropMenu.h"
#import "JMAuthVC.h"
#import "JMHomeModel.h"
#import "JMProductVC.h"
#import "JMCPIListVC.h"
#import "JMOrderModel.h"
#import "JMOrderInfoVC.h"
#import "JMTenLocationManager.h"
#import "JMExtInfoManager.h"
#import "JMBankAccountController.h"
#import "JMHomeFicoView.h"
#import "JMHomeCloudunView.h"
#import "JMHomeNoVerifyView.h"
#import "JMHomeOrderView.h"
#import "JMVerifyTopView.h"
#import "JMHomeTipsView.h"
#import "JMHomeWarmView.h"
#import "JMHomeApplyView.h"

@interface JMHomeVC ()<CLLocationManagerDelegate>{
    CGFloat top;
}
@property (nonatomic, strong) UIScrollView *mainSV;
@property (nonatomic, strong) JMHomeModel *model;
@property (nonatomic, strong) NSArray *repaidOrders;
@property (nonatomic, strong) NSMutableArray *popStrings;
@property (nonatomic, assign) BOOL needFresh;

@end

@implementation JMHomeVC
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.rdv_tabBarController setTabBarHidden:YES animated:YES];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.rdv_tabBarController setTabBarHidden:NO animated:YES];
    [self fetchData];
    
    JMExtInfoManager.sharedManager.vc = self;
    [JMExtInfoManager.sharedManager checkExtExpired];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
//
//    if (JMProjectManager.sharedJMProjectManager.loginUser.isFirstVerify) {
//        //认证成功跳转 产品打包页
//        JMProductVC *vc = JMProductVC.new;
//        [self.navigationController pushViewController:vc animated:YES];
//        JMProjectManager.sharedJMProjectManager.loginUser.isFirstVerify = NO;
//    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //基本配置
    self.view.backgroundColor = Hex_Str_COLOR(@"#F7F7F5");
    self.backBtn.hidden = YES;
    self.popStrings = @[].mutableCopy;
    
    ///首页所有弹窗队列
    @weakify(self)
    [[NSNotificationCenter defaultCenter]addObserverForName:@"AlertDismiss" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        @strongify(self);
        if(self.popStrings.count){
            delayOperation(0.1, ^{
                [self beginAlert];
            });
        }
    }];
    //获取数据
    [self fetchData];
    
    
}

-(void)fetchData{
    //1.先获取下一步填写信息的step 100 显示提交申请后页面 否则显示默认
    self.model = [JMHomeModel new];
    
    dispatch_group_t group = dispatch_group_create();
    //1.获取下一步填写信息
    dispatch_group_enter(group);
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(@"/api/loan/get-next-step2") params:nil success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        
        if([(NSString *)dataDic[@"step"] isEqualToString:@"100"]){
            JMProjectManager.sharedJMProjectManager.loginUser.isVerified = YES;
        }else{
            self.model.stepString = (NSString *)dataDic;
            JMProjectManager.sharedJMProjectManager.loginUser.isVerified = NO;
        }
        dispatch_group_leave(group);
    } fail:^(NSString * _Nonnull errorMsg) {
        dispatch_group_leave(group);
    }];
    
    
    //2.获取首页需要的用户信用额度
    dispatch_group_enter(group);
    [[JMBaseRequest sharedInstance]requestBasePost:BasePostRequestUrl(@"/api/user/creditInfo") params:nil success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        self.model.extraAmountIsNotReminded = [dataDic safeBoolForKey:@"extraAmountIsNotReminded"];
        self.model.used = dataDic[@"used"];
        self.model.unused = dataDic[@"unused"];
        self.model.total = dataDic[@"total"];
        self.model.locking = dataDic[@"locking"];
        dispatch_group_leave(group);
        
    } fail:^(NSString * _Nonnull errorMsg) {
        dispatch_group_leave(group);
    }];
    
    
    //    //3.检查用户放款状态
    dispatch_group_enter(group);
    [[JMBaseRequest sharedInstance]requestBasePost:BasePostRequestUrl(@"/api/order/check-user-loan-status") params:nil success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        self.model.loanFail = [dataDic safeBoolForKey:@"loanFail"];
        
        dispatch_group_leave(group);
    } fail:^(NSString * _Nonnull errorMsg) {
        dispatch_group_leave(group);
    }];
    
    //5./api/common/isShowCREntrance 检查是否展示信用报告
    dispatch_group_enter(group);
    NSDictionary *dic = @{
        @"partnerId": @"2fec752cc5d9a2774911936cfb21dd39",
        @"pageType": @(2).stringValue
    };
    [[JMBaseRequest sharedInstance]requestBasePost:BasePostRequestUrl(@"/api/common/isShowCREntrance") params:dic successResult:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        self.model.showReportView = [dataDic safeBoolForKey:@"data"];
        
        dispatch_group_leave(group);
        
    } fail:^(NSString * _Nonnull errorMsg) {
        dispatch_group_leave(group);
        
    }];
    
    //7.待还款借款列表
    dispatch_group_enter(group);
    [[JMBaseRequest sharedInstance]requestBasePost:BasePostRequestUrl(@"/api/order/repaid-order2") params:nil success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        self.repaidOrders = [JMOrderModel mj_objectArrayWithKeyValuesArray:dataDic[@"repaidOrders"]];
        dispatch_group_leave(group);
        
    } fail:^(NSString * _Nonnull errorMsg) {
        dispatch_group_leave(group);
    }];
    
    //8.是否跳CPI
    [[JMBaseRequest sharedInstance]requestBasePost:BasePostRequestUrl(@"/api/index/isJumpProductOrCpi") params:nil success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        self.model.CPIString = dataDic;
    } fail:nil];
    
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self.popStrings removeAllObjects];
        [self stopAnimating];
        [[JMBaseRequest sharedInstance]requestBasePost:BasePostRequestUrl(homePop) params:nil success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
            [self stopAnimating];
            self.model.ficoPop =                [dataDic safeBoolForKey:@"ficoPop"];
            self.model.firstLoanSuccess =       [dataDic safeBoolForKey:@"firstLoanSuccess"];
            self.model.raiseAmount =            [dataDic safeBoolForKey:@"raiseAmount"];
            self.model.cloudunPayed =           [dataDic safeBoolForKey:@"cloudunPayed"];
            self.model.showLoanFailAlert =      [dataDic safeBoolForKey:@"loanFail"];
            self.model.hadLoan =                [dataDic safeBoolForKey:@"hadLoan"];
            //            self.model.raiseAmount = YES;
            
            self.model.fICOPayed =              [dataDic safeBoolForKey:@"fICOPayed"];
            self.model.loanCheck =              [dataDic safeBoolForKey:@"loanCheck"];
            [self setUI];
            if(self.model.loanCheck == true){
                [self.popStrings addObject:@"loanCheck"];
            }
            if(self.model.showLoanFailAlert == true){
                [self.popStrings addObject:@"loanFail"];
            }
            if (self.model.raiseAmount == true || self.model.extraAmountIsNotReminded==true){
                [self.popStrings addObject:@"raiseAmount"];
            }
            if (self.model.ficoPop == true){
                [self.popStrings addObject:@"ficoPop"];
            }
            delayOperation(0.5, ^{
                [self beginAlert];
            });
            self.needFresh = NO;
        } fail:^(NSString * _Nonnull errorMsg) {
            
        }];
    });
}

-(void)beginAlert{
    
    if(self.popStrings.count){
        @weakify(self)
        NSString *string = self.popStrings.firstObject;
        if([string isEqualToString:@"loanCheck"]){
            //预检 未通过
            [JMPublicAlertView showAlertWithFrame:(CGRectMake(0, 0, kAppW()-40, 246)) Title:@"" subTitle:@"Lo sentimos, actualmente no hay ninguno préstamo disponible para usted" BottomBtns:@[@"Puntuación de crédito"] Position:(JMPublicAlertViewPositionCenter) btnDirection:(JMPublicAlertViewButtonDirectionHor)btnActionBlock:^(NSInteger btnTag) {
                //查询信用分
                @strongify(self);
                [ self openCreditUrl:@"2"];
            }];
        }
        if([string isEqualToString:@"loanFail"]){
            NSString *saveDateString = JMProjectManager.sharedJMProjectManager.loginUser.loanFailPopDataString;
            NSString *token = JMProjectManager.sharedJMProjectManager.loginUser.token;
            
            if (!saveDateString.isShowed) {
                JMProjectManager.sharedJMProjectManager.loginUser.loanFailPopDataString = [NSString currentDateString];
                [JMProjectManager.sharedJMProjectManager.loginUser save];
                
                [JMPublicAlertView showAlertWithFrame:(CGRectMake(0, 0, kAppW()-40, 246)) Title:@"" subTitle:@"Lo sentimos, su solicitud de préstamo no fue aprobada." BottomBtns:@[@"Puntuación de crédito"] Position:(JMPublicAlertViewPositionCenter) btnDirection:(JMPublicAlertViewButtonDirectionHor)btnActionBlock:^(NSInteger btnTag) {
                    //查询信用分
                    @strongify(self)
                    [self openCreditUrl:@"1"];
                }];
            }
        }
        if([string isEqualToString:@"raiseAmount"]){
            
            [JMPublicAlertView showAlertWithFrame:(CGRectMake(0, 0, kAppW()-40, 246)) Title:@"" subTitle:@"Gracias por pagar La cuota de su préstamo se ha incrementado 400 a 1000 pesos" BottomBtns:@[@"5s"] Position:(JMPublicAlertViewPositionCenter) btnDirection:(JMPublicAlertViewButtonDirectionHor)btnActionBlock:^(NSInteger btnTag) {
                
            }];
        }
        if([string isEqualToString:@"ficoPop"]){
            
            NSString *saveDateString = JMProjectManager.sharedJMProjectManager.loginUser.ficoPopDataString;
            if (!saveDateString.isShowed) {
                JMProjectManager.sharedJMProjectManager.loginUser.ficoPopDataString = [NSString currentDateString];
                [JMProjectManager.sharedJMProjectManager.loginUser save];
                [JMPublicAlertView showAlertWithFrame:(CGRectMake(0, 0, kAppW()-40, 246)) Title:@"" subTitle:@"¿Quiere aumentar rápidamente la cuota de su crédito? Pruebe a autorizar el acceso a los informes de puntuación de Fico" BottomBtns:@[@"Puntuación de crédito"] Position:(JMPublicAlertViewPositionCenter) btnDirection:(JMPublicAlertViewButtonDirectionHor)btnActionBlock:^(NSInteger btnTag) {
                    //查询信用分
                    @strongify(self);
                    [self openCreditUrl:@"1"];
                    
                }];
            }
        }
        delayOperation(0.1, ^{
            if (self.popStrings.count) {
                [self.popStrings removeObjectAtIndex:0];
            }
        });
    }
    
}

-(void)setUI{
    
    [_mainSV removeAllSubviews];
    _mainSV = nil;
    
    _mainSV = [[UIScrollView alloc]initWithFrame:(CGRectMake(0, 0, kAppW(), kAppH()-TAB_BAR_HEIGHT()))];
    _mainSV.bounces = NO;
    _mainSV.backgroundColor = WhiteColor();
    if (@available(iOS 11.0, *)) {
        self.mainSV.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = false;
    }
    [self.view addSubview:_mainSV];
    
    
    BOOL showFico = _model.hadLoan==true&&_model.fICOPayed==false;
    BOOL showCloundun  = _model.hadLoan==false&&_model.cloudunPayed==false;
    
    if(self.model.showReportView==NO){//如果返回为false 则直接隐藏信用报告区域
        showFico= showCloundun =NO;
    }
    if(JMProjectManager.sharedJMProjectManager.loginUser.isVerified){//认证通过UI
        JMVerifyTopView *topV = [[JMVerifyTopView alloc]initWithFrame:(CGRectMake(0, 0, kAppW(), 306)) model:self.model];
        [self.mainSV addSubview:topV];
        top = topV.bottom+16;
        
        if (self.model.loanFail==YES) {
            JMHomeWarmView *view = [[JMHomeWarmView alloc]initWithFrame:(CGRectMake(12, top, kAppW()-24, 119))];
            [_mainSV addSubview:view];
            top = view.bottom+15;
        }
        if(self.repaidOrders.count){
            JMHomeTipsView*tipsV = [[JMHomeTipsView alloc]initWithFrame:(CGRectMake(12, top, kAppW()-24, 119))];
            [_mainSV addSubview:tipsV];
            top = tipsV.bottom+15;
        }
        if(showFico){
            JMHomeFicoView* ficoV = [[JMHomeFicoView alloc]initWithFrame:(CGRectMake(0, top, kAppW(), 160))];
            [_mainSV addSubview:ficoV];
            top = ficoV.bottom+15;
        }
        //        if(showCloundun){
        JMHomeCloudunView* cloundunView = [[JMHomeCloudunView alloc]initWithFrame:(CGRectMake(9, top, kAppW()-18, ScaleW(119)))];
        [_mainSV addSubview:cloundunView];
        top = cloundunView.bottom+15;
        //        }
        JMHomeApplyView* applyV = [[JMHomeApplyView alloc]initWithFrame:(CGRectMake(0, top, kAppW(), ScaleW(32+137))) model:self.model];
        [_mainSV addSubview:applyV];
        top = applyV.bottom+15;
        
        if(self.repaidOrders.count){
            JMHomeOrderView*orderView = [[JMHomeOrderView alloc]initWithFrame:(CGRectMake(0, top, kAppW(), 20))andModelArray:self.repaidOrders];
            [_mainSV addSubview:orderView];
            top = orderView.bottom+15;
        }
        [self.mainSV addSubview:self.footerView];
        self.footerView.top = top;
        self.mainSV.contentSize = CGSizeMake(kAppW(), self.footerView.bottom+50);
        
    }else{
        JMHomeNoVerifyView *noVerifyView = [[JMHomeNoVerifyView alloc]initWithNeedCloudun:YES];
        [_mainSV addSubview:noVerifyView];
        _mainSV.contentSize = CGSizeMake(kAppW(), noVerifyView.height);
    }
    
}
-(void)delegateBtnClick{
    [JMCommonMethod presentWebviewWithUrl:serviceUrlWith(loginPrivacyAgreement) andTitle:@"Politica de privacidad"];
}

@end
